﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using IRepository;
using MvcUI.Models;
using Entities;
namespace MvcUI.Controllers
{
    /// <summary>
    /// 
    /// </summary>
    public class MUserRoleController : BaseController
    {
        /// <summary>
        /// 
        /// </summary>
        private IUserRepository userRepository;
        /// <summary>
        /// 
        /// </summary>
        private IRoleRepository roleRepository;
        /// <summary>
        /// 
        /// </summary>
        private IUserRoleRepository userRoleRepository;

        /// <summary>
        /// 
        /// </summary>
        private static string userID = "-1";
        /// <summary>
        /// 
        /// </summary>
        private static string roleID = "-1";

        /// <summary>
        /// 
        /// </summary>
        /// <param name="_userRepository"></param>
        /// <param name="_roleRepository"></param>
        /// <param name="_userRoleRepository"></param>
        public MUserRoleController(IUserRepository _userRepository, IRoleRepository _roleRepository, IUserRoleRepository _userRoleRepository)
        {
            this.userRepository = _userRepository;
            this.roleRepository = _roleRepository;
            this.userRoleRepository = _userRoleRepository;
            pageSize = 20;
        }

        /// <summary>
        /// 进入用户与角色关系设置页的首页，默认显示第一页用户
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Index()
        {

            ListUserViewModel vm = new ListUserViewModel
            {
                Users = userRepository.GetList("1=1")
                    .OrderBy(p => p.UserName)
                    .Skip((1 - 1) * pageSize)
                    .Take(pageSize),
                PagingInfo = new PagingInfo
                {
                    TotalItems = userRepository.GetRecordCount("1=1"),
                    CurrentPage = 1,
                    ItemsPerPage = pageSize,
                    OrderField = "UserName",
                    OrderDirection = "desc",
                }

            };
            return View(vm);
        }

        /// <summary>
        /// 根据用户添加角色的tab中的用户区域
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult UsersMaster()
        {
            ListUserViewModel vm = new ListUserViewModel
            {
                Users = userRepository.GetList("1=1")
                    .OrderBy(p => p.UserName)
                    .Skip((1 - 1) * pageSize)
                    .Take(pageSize),
                PagingInfo = new PagingInfo
                {
                    TotalItems = userRepository.GetRecordCount("1=1"),
                    CurrentPage = 1,
                    ItemsPerPage = pageSize,
                    OrderField = "UserName",
                    OrderDirection = "desc",
                }

            };
            return View(vm);
        }

        /// <summary>
        /// 根据用户添加角色的tab中的用户区域
        /// </summary>
        /// <param name="formCollection">翻页和排序及请求参数集合</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UsersMaster(FormCollection formCollection)
        {
            int pageIndex = Request["pageNum"] == null ? 1 : Convert.ToInt32(Request["pageNum"]);
            pageSize = Request["numPerPage"] == null ? pageSize : Convert.ToInt32(Request["numPerPage"]);
            string orderField = Request["orderField"] == null ? "UserName" : Request["orderField"].ToString();
            string orderDirection = Request["orderDirection"] == null ? "asc" : Request["orderDirection"].ToString();
            string keywords = Request["keywords"] == null ? "" : Request["keywords"].ToString();
            string strWhere = String.IsNullOrEmpty(keywords) ? "1=1" : "UserName='" + keywords + "'";

            ListUserViewModel vm = new ListUserViewModel
            {
                Users = userRepository.GetListByPage(strWhere, orderField + " " + orderDirection, (pageIndex - 1) * pageSize + 1, pageIndex * pageSize).AsEnumerable(),
                KeyWord = keywords,
                PagingInfo = new PagingInfo
                {
                    TotalItems = userRepository.GetRecordCount(strWhere),
                    CurrentPage = pageIndex,
                    ItemsPerPage = pageSize,
                    OrderField = orderField,
                    OrderDirection = orderDirection,
                }

            };
            return View(vm);
        }

        /// <summary>
        /// 根据用户添加角色的tab中的角色区域
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Roles(string id = "-1")
        {
            userID = id;
            Session["_userID"] = id;
            ListRoleViewModel vm = new ListRoleViewModel
           {

               Roles = userRoleRepository.GetRolesByUserID(id)
                   .OrderBy(p => p.Name)
                   .Skip((1 - 1) * pageSize)
                   .Take(pageSize),
               PagingInfo = new PagingInfo
               {
                   TotalItems = userRoleRepository.GetRolesByUserID(id).Count(),
                   CurrentPage = 1,
                   ItemsPerPage = pageSize,
                   OrderField = "Name",
                   OrderDirection = "desc",
               }

           };
            ViewData["Name"] = userRepository.Get(userID).UserName;
            return View(vm);
        }

        /// <summary>
        /// 根据用户添加角色的tab中的角色区域
        /// </summary>
        /// <param name="formCollection">翻页和排序及查询参数集合</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Roles(FormCollection formCollection)
        {
            int pageIndex = Request["pageNum"] == null ? 1 : Convert.ToInt32(Request["pageNum"]);
            pageSize = Request["numPerPage"] == null ? pageSize : Convert.ToInt32(Request["numPerPage"]);
            string orderField = Request["orderField"] == null ? "Name" : Request["orderField"].ToString();
            string orderDirection = Request["orderDirection"] == null ? "asc" : Request["orderDirection"].ToString();
            string keywords = Request["keywords"] == null ? "" : Request["keywords"].ToString();
            string strWhere = String.IsNullOrEmpty(keywords) ? "1=1" : "Name='" + keywords + "'";

            ListRoleViewModel vm = new ListRoleViewModel
            {
                Roles = userRoleRepository.GetRolesByUserID(userID)
                    .Where(s => String.IsNullOrEmpty(keywords) ? 1 == 1 : s.Name == keywords)
                    .OrderBy(p => p.Name)
                    .Skip((pageIndex - 1) * pageSize)
                    .Take(pageSize),

                KeyWord = keywords,
                PagingInfo = new PagingInfo
                {
                    TotalItems = userRoleRepository.GetRolesByUserID(userID).Where(s => String.IsNullOrEmpty(keywords) ? 1 == 1 : s.Name == keywords).Count(),
                    CurrentPage = pageIndex,
                    ItemsPerPage = pageSize,
                    OrderField = orderField,
                    OrderDirection = orderDirection,
                }

            };
            ViewData["Name"] = userRepository.Get(userID).UserName;
            return View(vm);
        }

        /// <summary>
        /// 根据用户添加角色弹出dialog显示未添加的角色区域
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult AddRoles(string id = "-1")
        {
            userID = id;
            ListRoleViewModel vm = new ListRoleViewModel
            {

                Roles = userRoleRepository.GetRolesNotInUser(id)
                    .OrderBy(p => p.Name)
                    .Skip((1 - 1) * pageSize)
                    .Take(pageSize),
                PagingInfo = new PagingInfo
                {
                    TotalItems = userRoleRepository.GetRolesNotInUser(id).Count(),
                    CurrentPage = 1,
                    ItemsPerPage = pageSize,
                    OrderField = "Name",
                    OrderDirection = "desc",
                }

            };
            return View(vm);
        }

        /// <summary>
        /// 根据用户添加角色弹出dialog显示未添加的角色区域
        /// </summary>
        /// <param name="formCollection">翻页和排序及查询参数集合</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AddRoles(FormCollection formCollection)
        {
            int pageIndex = Request["pageNum"] == null ? 1 : Convert.ToInt32(Request["pageNum"]);
            pageSize = Request["numPerPage"] == null ? pageSize : Convert.ToInt32(Request["numPerPage"]);
            string orderField = Request["orderField"] == null ? "Name" : Request["orderField"].ToString();
            string orderDirection = Request["orderDirection"] == null ? "asc" : Request["orderDirection"].ToString();
            string keywords = Request["keywords"] == null ? "" : Request["keywords"].ToString();
            string strWhere = String.IsNullOrEmpty(keywords) ? "1=1" : "Name='" + keywords + "'";

            ListRoleViewModel vm = new ListRoleViewModel();
            if (orderDirection.Equals("desc"))
            {
                vm.Roles = userRoleRepository.GetRolesNotInUser(userID)
                    .Where(s => String.IsNullOrEmpty(keywords) ? 1 == 1 : s.Name == keywords)
                   .OrderByDescending(p => p.Name)
                    .Skip((pageIndex - 1) * pageSize)
                    .Take(pageSize);
            }
            else
            {

                vm.Roles = userRoleRepository.GetRolesNotInUser(userID)
                    .Where(s => String.IsNullOrEmpty(keywords) ? 1 == 1 : s.Name == keywords)
                    .OrderBy(p => p.Name)
                    .Skip((pageIndex - 1) * pageSize)
                    .Take(pageSize);
            }

            vm.KeyWord = keywords;
            vm.PagingInfo = new PagingInfo
             {
                 TotalItems = userRoleRepository.GetRolesNotInUser(userID).Where(s => s.Name == keywords).Count(),
                 CurrentPage = pageIndex,
                 ItemsPerPage = pageSize,
                 OrderField = orderField,
                 OrderDirection = orderDirection,
             };



            return View(vm);
        }

        /// <summary>
        /// 为用户添加角色操作
        /// </summary>
        /// <param name="formCollection">角色ID集合</param>
        /// <returns></returns>
        [HttpPost]
        public string Add(FormCollection formCollection)
        {
            List<string> listID = Request.Params["ids"] == null ? null : Request.Params["ids"].Split(',').ToList();
            bool result = false;
            foreach (string s in listID)
            {

                UserRole ur = new UserRole
                {
                    UserID = userID,
                    RoleID = s,
                    Creator = this.User.ID,
                    CreateTime = DateTime.Now,
                    Updator = this.User.ID,
                    UpdateTime = DateTime.Now
                };
                result = userRoleRepository.Add(ur);
                if (!result)
                {
                    break;
                }
            }
            return result ? SetOperateResultNav("200", "操作成功", "addRolesToUser", "", "", "closeCurrent", "") : SetOperateResultNav("300", "操作意外终止", "addRolesToUser", "", "", "", "");
        }

        /// <summary>
        /// 删除用户所具备的角色操作
        /// </summary>
        /// <param name="id">角色ID</param>
        /// <returns></returns>
        [HttpPost]
        public string DeleteByRoleID(string id = "-1")
        {
            bool result = userRoleRepository.Delete(userID, id);
            return result ? SetOperateResultNav("200", "操作成功", "jbsxBox3", "", "", "", "") : SetOperateResultNav("300", "操作意外终止", "addRolesToUser", "", "", "", "");
        }

        /// <summary>
        /// 批量删除用户所具备的角色
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string RemoveRolesBatch()
        {
            var ids = Request.Params["ids1"] == null ? null : Request.Params["ids1"].Split(',');
            bool result = userRoleRepository.DeleteByUserAndRoles(userID, ids.ToList());
            if (result)
            {
                return SetOperateResultNav("200", "操作成功", "jbsxBox3", "", "", "", "");
            }
            else
            {
                return SetOperateResultNav("300", "操作失败", "", "", "", "", "");
            }
        }

        /// <summary>
        /// 根据角色添加用户的角色区域
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult RolesMaster()
        {
            ListRoleViewModel vm = new ListRoleViewModel
            {
                Roles = ((IEnumerable<Entities.Role>)roleRepository.GetList("1=1"))
                     .OrderBy(p => p.Name)
                     .Skip((1 - 1) * pageSize)
                     .Take(pageSize),
                PagingInfo = new PagingInfo
                {
                    TotalItems = roleRepository.GetRecordCount("1=1"),
                    CurrentPage = 1,
                    ItemsPerPage = pageSize,
                    OrderField = "Name",
                    OrderDirection = "desc",
                }

            };
            return View(vm);
        }

        /// <summary>
        /// 根据角色添加用户的角色区域
        /// </summary>
        /// <param name="formCollection">翻页和排序及查询参数集合</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult RolesMaster(FormCollection formCollection)
        {
            int pageIndex = Request["pageNum"] == null ? 1 : Convert.ToInt32(Request["pageNum"]);
            pageSize = Request["numPerPage"] == null ? pageSize : Convert.ToInt32(Request["numPerPage"]);
            string orderField = Request["orderField"] == null ? "Name" : Request["orderField"].ToString();
            string orderDirection = Request["orderDirection"] == null ? "asc" : Request["orderDirection"].ToString();
            string keywords = Request["keywords"] == null ? "" : Request["keywords"].ToString();
            string strWhere = String.IsNullOrEmpty(keywords) ? "1=1" : "Name='" + keywords + "'";

            ListRoleViewModel vm = new ListRoleViewModel
            {
                Roles = ((IEnumerable<Entities.Role>)roleRepository
                    .GetListByPage(strWhere, orderField + " " + orderDirection, (pageIndex - 1) * pageSize + 1, pageIndex * pageSize)),
                KeyWord = keywords,
                PagingInfo = new PagingInfo
                {
                    TotalItems = roleRepository.GetRecordCount(strWhere),
                    CurrentPage = pageIndex,
                    ItemsPerPage = pageSize,
                    OrderField = orderField,
                    OrderDirection = orderDirection,
                }
            };
            return View(vm);
        }

        /// <summary>
        /// 根据角色添加用户的tab中的用户区域
        /// </summary>
        /// <param name="id">角色ID</param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Users(string id = "-1")
        {
            roleID = id;
            Session["_roleID"] = id;
            ListUserViewModel vm = new ListUserViewModel
            {
                Users = userRoleRepository.GetUsersByRoleID(id)
                    .OrderBy(p => p.UserName)
                    .Skip((1 - 1) * pageSize)
                    .Take(pageSize),
                PagingInfo = new PagingInfo
                {
                    TotalItems = userRoleRepository.GetUsersByRoleID(id).Count(),
                    CurrentPage = 1,
                    ItemsPerPage = pageSize,
                    OrderField = "UserName",
                    OrderDirection = "desc",
                }
            };
            ViewData["Name"] = ((Entities.Role)roleRepository.Get(roleID)).Name;
            return View(vm);
        }

        /// <summary>
        /// 根据角色添加用户的tab中的用户区域
        /// </summary>
        /// <param name="formCollection">翻页和排序及查询参数集合</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Users(FormCollection formCollection)
        {
            int pageIndex = Request["pageNum"] == null ? 1 : Convert.ToInt32(Request["pageNum"]);
            pageSize = Request["numPerPage"] == null ? pageSize : Convert.ToInt32(Request["numPerPage"]);
            string orderField = Request["orderField"] == null ? "Name" : Request["orderField"].ToString();
            string orderDirection = Request["orderDirection"] == null ? "asc" : Request["orderDirection"].ToString();
            string keywords = Request["keywords"] == null ? "" : Request["keywords"].ToString();
            string strWhere = String.IsNullOrEmpty(keywords) ? "1=1" : "UserName='" + keywords + "'";

            ListUserViewModel vm = new ListUserViewModel
            {
                Users = userRoleRepository.GetUsersByRoleID(roleID)
                    .Where(s => String.IsNullOrEmpty(keywords) ? 1 == 1 : s.UserName == keywords)
                    .OrderBy(p => p.UserName)
                    .Skip((pageIndex - 1) * pageSize)
                    .Take(pageSize),

                KeyWord = keywords,
                PagingInfo = new PagingInfo
                {
                    TotalItems = userRoleRepository.GetRolesByUserID(roleID).Where(s => String.IsNullOrEmpty(keywords) ? 1 == 1 : s.Name == keywords).Count(),
                    CurrentPage = pageIndex,
                    ItemsPerPage = pageSize,
                    OrderField = orderField,
                    OrderDirection = orderDirection,
                }
            };
            ViewData["Name"] = ((Entities.Role)roleRepository.Get(roleID)).Name;
            return View(vm);
        }

        /// <summary>
        /// 删除具有角色的用户
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns></returns>
        [HttpPost]
        public string DeleteByUserID(string id = "-1")
        {
            bool result = userRoleRepository.Delete(id, roleID);
            return result ? SetOperateResultNav("200", "操作成功", "jbsxBox3", "", "", "", "") : SetOperateResultNav("300", "操作意外终止", "addRolesToUser", "", "", "", "");
        }

        /// <summary>
        /// 批量删除具有角色的用户
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string RemoveUsersBatch()
        {
            var ids = Request.Params["ids5"] == null ? null : Request.Params["ids5"].Split(',');
            bool result = userRoleRepository.DeleteByRoleAndUsers(roleID, ids.ToList());
            if (result)
            {
                return SetOperateResultNav("200", "操作成功", "jbsxBox5", "", "", "", "");
            }
            else
            {
                return SetOperateResultNav("300", "操作失败", "", "", "", "", "");
            }
        }


        /// <summary>
        /// 根据角色添加用户弹出dialog显示未添加的用户区域
        /// </summary>
        /// <param name="id">角色ID</param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult AddUsers(string id = "-1")
        {
            roleID = id;
            ListUserViewModel vm = new ListUserViewModel
            {

                Users = userRoleRepository.GetUsersNotInRole(id)
                    .OrderBy(p => p.UserName)
                    .Skip((1 - 1) * pageSize)
                    .Take(pageSize),
                PagingInfo = new PagingInfo
                {
                    TotalItems = userRoleRepository.GetUsersNotInRole(id).Count(),
                    CurrentPage = 1,
                    ItemsPerPage = pageSize,
                    OrderField = "UserName",
                    OrderDirection = "desc",
                }

            };
            return View(vm);
        }

        /// <summary>
        /// 根据角色添加用户弹出dialog显示未添加的用户区域
        /// </summary>
        /// <param name="formCollection">翻页和排序及查询参数集合</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AddUsers(FormCollection formCollection)
        {
            int pageIndex = Request["pageNum"] == null ? 1 : Convert.ToInt32(Request["pageNum"]);
            pageSize = Request["numPerPage"] == null ? pageSize : Convert.ToInt32(Request["numPerPage"]);
            string orderField = Request["orderField"] == null ? "UserName" : Request["orderField"].ToString();
            string orderDirection = Request["orderDirection"] == null ? "asc" : Request["orderDirection"].ToString();
            string keywords = Request["keywords"] == null ? "" : Request["keywords"].ToString();
            string strWhere = String.IsNullOrEmpty(keywords) ? "1=1" : "UserName='" + keywords + "'";

            ListUserViewModel vm = new ListUserViewModel();
            if (orderDirection.Equals("desc"))
            {
                vm.Users = userRoleRepository.GetUsersNotInRole(roleID)
                    .Where(s => String.IsNullOrEmpty(keywords) ? 1 == 1 : s.UserName == keywords)
                   .OrderByDescending(p => p.UserName)
                    .Skip((pageIndex - 1) * pageSize)
                    .Take(pageSize);
            }
            else
            {

                vm.Users = userRoleRepository.GetUsersNotInRole(roleID)
                    .Where(s => String.IsNullOrEmpty(keywords) ? 1 == 1 : s.UserName == keywords)
                    .OrderBy(p => p.UserName)
                    .Skip((pageIndex - 1) * pageSize)
                    .Take(pageSize);
            }

            vm.KeyWord = keywords;
            vm.PagingInfo = new PagingInfo
            {
                TotalItems = userRoleRepository.GetUsersNotInRole(roleID).Where(s => s.UserName == keywords).Count(),
                CurrentPage = pageIndex,
                ItemsPerPage = pageSize,
                OrderField = orderField,
                OrderDirection = orderDirection,
            };
            return View(vm);
        }

        /// <summary>
        /// 为角色添加用户操作
        /// </summary>
        /// <param name="formCollection">用户ID集合</param>
        /// <returns></returns>
        [HttpPost]
        public string Add2(FormCollection formCollection)
        {
            List<string> listID = Request.Params["ids6"] == null ? null : Request.Params["ids6"].Split(',').ToList();
            bool result = false;
            foreach (string s in listID)
            {

                UserRole ur = new UserRole
                {
                    UserID = s,
                    RoleID = roleID,
                    Creator = this.User.ID,
                    CreateTime = DateTime.Now,
                    Updator = this.User.ID,
                    UpdateTime = DateTime.Now
                };
                result = userRoleRepository.Add(ur);
                if (!result)
                {
                    break;
                }
            }
            return result ? SetOperateResultNav("200", "操作成功", "addUsersToRole", "", "", "closeCurrent", "") : SetOperateResultNav("300", "操作意外终止", "addUsersToRole", "", "", "", "");
        }

    }
}
